<?php

namespace app\controllers\admin\uni\supplier;

use app\controllers\admin\base\AdminController;
use app\models\AdminSupplier as Model;
use app\models\Brand;
use app\models\product\Product;
use app\models\product\ProductCategory;
use app\models\SupplierAddress;
use app\models\SupplierCategory;
use app\models\SupplierImage;
use app\models\user\User;
use app\models\user\UserLevel;
use app\redis\Cache;
use app\redis\supplier\Check;

class SupplierController extends AdminController
{
    // 分类列表
    public function actionCategory()
    {
        $list = SupplierCategory::find()
            ->where(['status' => 1])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
            ->asArray()
            ->all();

        // 地区
        $address = SupplierAddress::find()
            ->where(['status' => 1])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
            ->asArray()
            ->all();

        return $this->success(['list' => $list, 'address' => $address]);
    }

    public function actionList()
    {
        $username = $this->post('username');
        $name = $this->post('name');
        $category_id = $this->post('category_id');
        $address_id = $this->post('address_id');
        $id = $this->post('id');
        $status = $this->post('status');
        $export = $this->post('export');

        $page = intval($this->post('page', $this->page));
        $page_size = intval($this->post('pageSize', $this->pageSize));

        $sort = $this->post('sort');

        $query = Model::find()
            ->where(['!=', 'status', Model::$statusMapping['DELETE']]);

        if ($status > Model::$statusMapping['ALL']) {
            $query->andWhere(['status' => $status]);
        }

        if ($sort) {
            $prop = substr($sort, 0, 1);
            $prop = $prop == '-' ? SORT_DESC : SORT_ASC;
            $order = substr($sort, 1);
            $query->orderBy([$order => $prop]);
        } else {
            $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC]);
        }

        if ($id) {
            $query->andWhere(['id' => $id]);
        }
        if (strlen($username) > 0) {
            $query->andWhere(['like', 'username', $username]);
        }
        if (strlen($name) > 0) {
            $query->andWhere(['like', 'name', $name]);
        }

        if ($category_id > 0) {
            $query->andWhere(['category_id' => $category_id]);
        }
        if ($address_id > 0) {
            $query->andWhere(['address_id' => $address_id]);
        }

        // export
        if ($export) {
            return $this->success($query->asArray()->all());
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $page_size);

        $list = $query->offset(($page - 1) * $page_size)
            ->limit($page_size)
            ->with(['category', 'descImage.image', 'address'])
            ->asArray()
            ->all();

        // 分类
        $category = SupplierCategory::find()
            ->where(['status' => 1])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
            ->asArray()
            ->all();

        // 地区
        $address = SupplierAddress::find()
            ->where(['status' => 1])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
            ->asArray()
            ->all();

        return $this->success([
            $this->totalCount   => $totalCount,
            $this->totalPage    => $totalPage,
            $this->list         => $list,
            'categoryList'      => $category,
            'addressList'      => $address,
        ]);

    }

    public function actionEdit()
    {
        $data = $this->post();

        $data['vip1_id'] = intval($data['vip1_id']);
        $data['vip6_id'] = intval($data['vip6_id']);

        try {
            if (isset($data['id']) && $data['id'] > 0) {
                $model = Model::findOne(['id' => $data['id']]);

                // image
                $image = SupplierImage::find()
                    ->where(['supplier_id' => $model->id])
                    ->select(['image_id'])
                    ->column();
                $image_add = array_diff($data['image'], $image);
                $image_sub = array_diff($image, $data['image']);

                if (!$model) {
                    return $this->fail('操作失败');
                }
            } else {
                $model = new Model();
                $model->password = md5('123456' . \Yii::$app->params['SUPPLIER_SALT']);
                $model->can_delete = 0;

                $image_add = $data['image'];
                $image_sub = [];
            }

            // 判断用户名重复
            if ($data['id'] > 0) {
                $has = Model::find()
                    ->where(['username' => $data['username']])
                    ->andWhere(['!=', 'id', $model->id])
                    ->andWhere(['!=', 'status', -99])
                    ->one();
            } else {
                $has = Model::find()
                    ->where(['username' => $data['username']])
                    ->andWhere(['!=', 'status', -99])
                    ->one();
            }
            if ($has) {
                return $this->fail('用户名已经存在!');
            }

            $data = ['AdminSupplier' => $data];
            if ($model->load($data) && $model->save()) {

                // image
                if ($image_sub) {
                    SupplierImage::deleteAll(['image_id' => $image_sub, 'supplier_id' => $model->id]);
                }
                if ($image_add) {
                    foreach ($image_add as $item) {
                        $i = new SupplierImage();
                        $i->supplier_id = $model->id;
                        $i->image_id = $item;
                        $i->save();
                    }
                }

                return $this->success($model, '操作成功');
            } else {
                throw new \Exception($model->getFirstError('username'));
            }
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    public function actionView()
    {
        $id = $this->post('id');
        $model = Model::find()
            ->where(['id' => $id])
            ->with(['image', 'image.image'])
            ->asArray()
            ->one();

        if ($model) {
            return $this->success($model);
        }

        return $this->fail('不存在该供应商');
    }

    public function actionRemove()
    {
        $id = $this->post('id');

        try {
            $model = Model::findOne(['id' => $id]);
            $model->status = Model::$statusMapping['DELETE'];
            $model->save();
            return $this->success($model, '删除成功');
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    public function actionStatusList()
    {
        return $this->success(Model::statusList());
    }

    public function actionChangeStatus()
    {
        $id = intval($this->post('id'));
        $status = intval($this->post('status'));

        try {
            $model = Model::findOne(['id' => $id]);
            $model->status = $status;
            $model->save();

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('操作错误: ' . $e->getMessage());
        }
    }

    public function actionChangeSort()
    {
        $id = intval($this->post('id'));
        $sort = intval($this->post('sort'));

        try {
            $model = Model::findOne(['id' => $id]);
            $model->sort = $sort;
            $model->save();

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('操作错误: ' . $e->getMessage());
        }
    }

    public function actionBatchRemove()
    {
        $ids = $this->post('ids');

        try {
            Model::updateAll(['status' => Model::$statusMapping['DELETE']], ['id' => $ids]);

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('删除错误: ' . $e->getMessage());
        }
    }

    // 审核消息提醒
    public function actionNotification()
    {
        $has = Check::getOne();

        if ($has) {
            Check::consume($has->id);
        }

        return $this->success(['has' => $has]);
    }

    public function actionCheckList()
    {
        $list = Check::getList();

        return $this->success(['list' => $list]);
    }

    public function actionCheckOk()
    {
        $id = $this->post('id');

        $check = Check::findOne(['id' => $id]);
        if ($check) {
            Check::consume($check->id);

            $model = null;
            if ($check->type == 'Brand') {
                $model = Brand::findOne(['id' => $check->model_id]);
            } else if ($check->type == 'Category') {
                $model = ProductCategory::findOne(['id' => $check->model_id]);
            } else if ($check->type == 'Product') {
                $model = Product::findOne(['id' => $check->model_id]);
            }
            if ($model) {
                $model->status = 1;
                $model->save();

                // 清除缓存
                Cache::flushAll();

                return $this->success();
            }
        }

        return $this->fail();
    }

    // 直推 业务员
    public function actionGetVip1List()
    {
        $list = User::find()
            ->where(['level' => UserLevel::$keys['vip1']])
            ->asArray()
            ->all();

        return $this->success(['list' => $list]);
    }

    // 直推中介
    public function actionGetVip6List()
    {
        $list = User::find()
            ->where(['level' => UserLevel::$keys['vip6']])
            ->asArray()
            ->all();

        return $this->success(['list' => $list]);
    }
}